var express = require('express');
var router = express.Router();
const { Course } = require('../models');
const { Op } = require('sequelize');
const { failureResponse, successResponse } = require('../utils/responses');
const { NotFoundError } = require('../utils/errors')

router.get('/', async (req, res) => {
  try {
    const query = req.query;
    const currentPage = Math.abs(Number(query.currentPage)) || 1
    const pageSize = Math.abs(Number(query.pageSize)) || 10
    const offset = (currentPage - 1) * pageSize;
    const condition = {
      attributes: { exclude: ['CategoryId', 'UserId', 'content'] },
      order: [['id', 'DESC']],
      limit: pageSize,
      offset: offset,
      where: {}
    }
    if (query.name) {
      condition.where.name = {
        [Op.like]: `%${query.name}%`
      }
    }
    const { count, rows } = await Course.findAndCountAll(condition);
    successResponse(res, '搜索课程成功', {
      articles: rows,
      pagination: {
        pageSize,
        currentPage,
        total: count
      }
    });
  } catch (error) {
    failureResponse(res, error);
  }
})

module.exports = router;